<template>
  <div class="pageOut">
    <div class="pageIn">
      <el-form :inline="true" :model="formSearch" size="small">
        <el-form-item>
          <el-input
            v-model="formSearch.role_name"
            placeholder="搜索角色名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" @click="search">查询</el-button>
          <el-button
            icon="el-icon-plus"
            type="primary"
            @click="handleAdd"
            v-show="permission.add"
            >新增角色</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        border
        ref="table"
        :height="height - 170"
        :data="tableData"
        :header-cell-style="{ background: '#FAFAFA', color: '#606266' }"
        v-loading="loading"
        element-loading-background="rgba(255, 255, 255, 0.5)"
        style="width: 100%"
      >
        <el-table-column prop="id" width="150" label="序号"></el-table-column>
        <el-table-column prop="role_name" label="角色名称"></el-table-column>
        <el-table-column
          prop="create_time"
          :show-overflow-tooltip="tooltip"
          label="手机号"
        ></el-table-column>
        <el-table-column fixed="right" label="操作" width="260" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="powerEdit(scope.row)"
              v-show="permission.powerlist"
              >权限分配</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="handleEdit(scope.row)"
              v-show="permission.edit"
              >修改</el-button
            >
            <el-button
              type="danger"
              size="mini"
              @click="handleDel(scope.row.id)"
              v-show="permission.del"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>

      <!-- 角色添加和角色编辑 -->
      <el-dialog
        :title="type === 'add' ? '添加角色' : '修改角色'"
        :visible.sync="visible"
        @close="onCancel('ruleForm')"
        width="550px"
      >
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          size="mini"
          label-width="120px"
        >
          <el-form-item
            label="角色名称"
            prop="role_name"
            style="margin-bottom: 30px"
          >
            <el-input
              clearable
              v-model="ruleForm.role_name"
              placeholder="请输入角色名称"
              style="width: 250px"
            ></el-input>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="onCancel('ruleForm')" size="small"
            >取 消</el-button
          >
          <el-button
            type="primary"
            size="small"
            @click="onConfirm('ruleForm')"
            :loading="confirmLoading"
            >{{ confirmLoading ? "提交中 ..." : "确 定" }}</el-button
          >
        </div>
      </el-dialog>

      <!-- 分配权限弹出框 -->
      <div class="power_add">
        <el-dialog
          title="分配权限"
          :visible.sync="powerVisible"
          width="30%"
          custom-class="abow_dialog"
          @close="
            nodeSelected = [];
            half_nodeSelected = [];
          "
        >
          <div class="block_node">
            <el-tree
              ref="tree"
              :data="nodelist"
              icon-class="el-icon-setting"
              node-key="id"
              show-checkbox
              :props="defaultProps"
              :default-checked-keys="nodeSelected"
              :default-expanded-keys="half_nodeSelected"
              :expand-on-click-node="false"
            />
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button
              @click="
                powerVisible = false;
                nodeSelected = [];
                half_nodeSelected = [];
              "
              >取 消</el-button
            >
            <el-button type="primary" @click="savePower">确 定</el-button>
          </span>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import {
  authRoleList,
  roleAdd,
  roleEdit,
  roleDel,
  authMenuList,
  authAllocationList,
  authAllocationSet,
  MAIN,
} from "../../utils/api";

export default {
  name: "AuthRole",
  props: ["height"],
  data() {
    return {
      tableData: [],
      tooltip: true, //内容过长被隐藏时显示 tooltip
      loading: true, //显示加载表格
      pageSize: 10, //每页多少条
      currentPage: 1, //当前第几页
      pageSizes: [10, 20, 30, 40, 50], //每页选择条数
      total: 0, //共多少条
      errImg: 'this.src="' + require("../../../static/img/user.png") + '"',
      permission: {
        add: false,
        edit: false,
        del: false,
        powerlist: false,
      }, //权限
      formSearch: {
        role_name: "",
      }, //搜索
      //编辑弹窗
      visible: false,
      confirmLoading: false,
      type: "",
      userinfo: {},
      currentRow: {}, //当前行数据信息
      ruleForm: {
        role_name: "",
      }, //添加和修改的表单
      rules: {
        role_name: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
      },
      powerVisible: false,
      nodelist: [],
      defaultProps: {
        children: "Child",
        label: "node_name",
      },
      nodeSelected: [],
      half_nodeSelected: [],
    };
  },

  mounted() {
    this.getResource();
  },
  methods: {
    //获取权限资源
    getResource() {
      // console.log(this.$route.name);
      this.loading = true;
      const userinfo = JSON.parse(sessionStorage.getItem("userInfo")); //解密,获取用户登录信息
      this.userinfo = userinfo;
      let arr = userinfo.menu_id.split(",");
      // console.log(arr)
      // 新增角色 78
      // 修改角色 79
      // 删除角色 80
      // 权限分配 81
      if (arr.indexOf("78") > -1) {
        this.permission.add = true;
      }
      if (arr.indexOf("79") > -1) {
        this.permission.edit = true;
      }

      if (arr.indexOf("80") > -1) {
        this.permission.del = true;
      }

      if (arr.indexOf("81") > -1) {
        this.permission.powerlist = true;
      }

      this.getData();
    },
    //获取初始数据
    getData() {
      this.loading = true;
      let params = {
        role_name: this.formSearch.role_name,
        pageNumber: this.currentPage,
        pageSize: this.pageSize,
      };
      this.postRequest(authRoleList, params, MAIN).then((res) => {
        if (res.code == 200) {
          // console.log(res);
          this.tableData = res.data.list;
          this.total = res.data.count;
          this.loading = false;
          this.$nextTick(() => {
            //避免表格表头样式错乱
            if (this.$refs.table) this.$refs.table.doLayout();
          });
        }
      });
    },

    //分页
    handleSizeChange(val) {
      //每页 ${val} 条
      this.pageSize = val;
      this.getData();
    },
    handleCurrentChange(val) {
      //当前页
      this.currentPage = val;
      this.getData();
    },
    //查询
    search() {
      this.getData();
    },
    //新增
    handleAdd() {
      this.type = "add";
      this.currentRow = {};
      this.visible = true;
    },
    //编辑
    handleEdit(row) {
      this.type = "edit";
      this.currentRow = row;
      this.visible = true;
      this.ruleForm = {
        role_name: row.role_name,
      };
    },
    //删除
    handleDel(id) {
      let parm = {
        id: id,
        userId: this.userinfo.id,
      };
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.postRequest(roleDel, parm, MAIN).then((res) => {
          // console.log(res);
          if (res.code == 200) {
            this.$notify({
              title: "删除成功",
              message: res.msg,
              type: "success",
            });
            this.getData();
          }
        });
      }).catch(() => {});
    },

    onConfirm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          // setTimeout(() => this.onCancel(formName), 1000);
          if (this.type == "add") {
            this.roleAdd();
          } else if (this.type == "edit") {
            this.roleEdit();
          }
        } else {
          return false;
        }
      });
    },
    // 添加
    roleAdd() {
      let params = {
        role_name: this.ruleForm.role_name,
        userId: this.userinfo.id,
      };

      this.postRequest(roleAdd, params, MAIN).then((res) => {
        // console.log(res);
        if (res.code == 200) {
          this.$notify({
            title: "添加成功",
            message: res.msg,
            type: "success",
          });
        }
        this.onReset();
        this.getData();
      });
    },
    // 编辑
    roleEdit() {
      let params = {
        id: this.currentRow.id,
        role_name: this.ruleForm.role_name,
        userId: this.userinfo.id,
      };

      this.postRequest(roleEdit, params, MAIN).then((res) => {
        // console.log(res);
        if (res.code == 200) {
          this.$notify({
            title: "编辑成功",
            message: res.msg,
            type: "success",
          });
        }
        this.onReset();
        this.getData();
      });
    },
    onCancel(formName) {
      this.$refs[formName].resetFields();
      this.onReset();
    },
    //清空重置表单
    onReset() {
      this.visible = false;
      this.confirmLoading = false;
      this.ruleForm = {
        role_name: "",
      };
    },
    // 权限分配
    powerEdit(row) {
      this.currentRow = row;
      console.log(row);
      this.nodelist = [];
      this.nodeSelected = [];
      this.half_nodeSelected = [];
      this.postRequest(authMenuList, {}, MAIN).then((res) => {
        if (res.code == 200) {
          // console.log(res, "getData2");
          this.nodelist = res.data;
          console.log(this.nodelist);
        }
      });
      this.postRequest(authAllocationList, { role_id: row.id }, MAIN).then(
        (res) => {
          if (res.code == 200) {
            console.log(res);
            // console.log(res.data.menu_id.split(","), "getData"); //转为数组
            // let a = res.data.menu_id.split(","); // 转为数组
            // // console.log(a.map(Number))
            // this.nodeSelected = [85, 9, 77]; //转为数字数组

            let b = res.data.ticks.split(","); // 转为数组 半选不包含父级的数组
            // this.half_nodeSelected = b.map(Number);

            // b.map(Number)转成数字数组
            this.$refs.tree.setCheckedKeys(b.map(Number)); //给接口获取的选中id添加选中效果

            var aa = this.$refs.tree.getHalfCheckedKeys(); //找到半选的id并给他打开的状态
            this.half_nodeSelected = aa;

            // console.log(b.map(Number))
          }
        }
      );

      this.powerVisible = true;
    },
    // 保存权限
    savePower() {
      var bb = this.$refs.tree.getCheckedKeys(); // .join(',') 全选
      var aa = this.$refs.tree.getHalfCheckedKeys(); //半选
      var dd = [...bb, ...aa];
      var cc = dd.join(",");
      let arr = [];
      let arr2 = [];
      bb.forEach((o) => {
        //全选
        arr.push(1);
      });

      aa.forEach((o) => {
        //半选
        arr2.push(2);
      });

      // console.log([...arr, ...arr2], "[...arr, ...arr2]");
      var role_id = this.currentRow.id;

      this.powerUpdate(role_id, cc, bb);
      // this.powerUpdate(role_id, cc, [...arr, ...arr2]);
      this.powerVisible = false;
    },
    powerUpdate(id, rule, ticks) {
      // console.log(ticks);
      // 权限更新
      var that = this;
      var param = {
        role_id: id,
        menu_id: rule,
        ticks: ticks.join(","),
        userId: this.userinfo.id,
      };
      // console.log(param);
      this.postRequest(authAllocationSet, param, MAIN).then((res) => {
        if (res.code == 200) {
          this.$notify({
            title: "分配权限成功",
            message: res.msg,
            type: "success",
          });
          this.getData();
        }
      });
    },
  },
};
</script>

<style scoped>
/deep/ .el-input-group__append,
.el-input-group__prepend {
  background-color: #1890ff;
  color: #fff;
  cursor: pointer;
}
/deep/ .el-input--mini .el-input__inner {
  height: 32px;
  line-height: 32px;
}
/deep/ input::-webkit-outer-spin-button,
/deep/ input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
/deep/ input[type="number"] {
  -moz-appearance: textfield;
}
</style>
